package com.meviewer.nt;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.webkit.JavascriptInterface;

import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meviewer.activity.BaseActivity;
import com.meviewer.activity.MainActivity;
import com.meviewer.activity.file.browser.CameraActivity;
import com.meviewer.activity.file.browser.FileBrowserActivity;
import com.meviewer.activity.file.browser.TargetPosActivity;
import com.meviewer.common.FileUtil;
import com.meviewer.common.Registry;
import com.meviewer.service.FindPosService;
import com.meviewer.service.GPSServiceWrapper;
import com.meviewer.service.JsonService;
import com.meviewer.service.JumpViewService;
import com.meviewer.service.ProcessingPakService;
import com.meviewer.service.ViewPointService;


/*import static com.meviewer.service.JsonService.getHttpRequestData;*/

import static com.meviewer.activity.MainActivity.__ginstance;
import static com.meviewer.service.JsonService.readJsonFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author hanhaoran
 */
public class JavaContext {
    private static boolean GPSFlag = true;

    private static final JavaContext INSTANCE = new JavaContext();

    public static JavaContext getInstance() {
        return INSTANCE;
    }



    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private JavaContext() {

    }

    @JavascriptInterface
    public void cameraTest() {
        __ginstance.checkPermissionAndCamera();
    }

    @JavascriptInterface
    public void OpenTargetPositioningAndroidWindow() {

        Intent targetPosActivity = new Intent(MainActivity.getInstance(), TargetPosActivity.class);

        MainActivity.getInstance().startActivityForResult(targetPosActivity, TargetPosActivity.ACTION_CODE);
    }
    @JavascriptInterface
    public void loadCamera() {
        //MainActivity.getInstance().testwrite();
        Intent t = new Intent(MainActivity.getInstance(), CameraActivity.class);
        MainActivity.getInstance().startActivityForResult(t, CameraActivity.CAMERA_REQUEST_CODE);

    }

    @JavascriptInterface
    public void consoleLook(String content) {
        System.out.println("打印结果:"+content);
    }

    //地名检索 通过地名查询文件名称及信息集合
    @JavascriptInterface
    public String  getFileForlderNamesByPosName(String name) {
        return FindPosService.getFileForlderNamesByPosName(name);
    }


    @JavascriptInterface
    public String getMarkImages(String path) {
        return FileUtil.getMarkImages(path);
    }

    @JavascriptInterface
    public String  getTypeByGeoJson(String path) {

        JSONObject obj = JSONObject.parseObject(FileUtil.read(path));
        JSONArray array = JSONArray.parseArray(Objects.requireNonNull(obj.get("features")).toString());

        return  Objects.requireNonNull(JSONObject.parseObject(Objects.requireNonNull(JSONObject.parseObject(array.get(0).toString()).get("geometry")).toString()).get("type")).toString();
    }
    @JavascriptInterface
    public String getImageTilesInfo(String path) {
        return MainActivity.getInstance().queryPakExtent(path);
    }


    @JavascriptInterface
    public String getHPYInfo(String path) {
        return MainActivity.getInstance().queryHPYExtent(path);
    }

    @JavascriptInterface
    public boolean saveLayerJsonFile(String path, String content) {
        path = path.replace("file:///","/");
        FileUtil.write(path,content);
        try {
            return true;
        }catch (Exception e){
            return false;
        }

    }
    @JavascriptInterface
    public boolean saveFile(String path, String content) {
        try {

            FileUtil.write(path,content);
            //写入外置SD卡 ，未完成
            /*savePasswordToSDCard("");*/
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @JavascriptInterface
    public String saveGPSData(String content) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date dt = new Date();
        String timestr = simpleDateFormat.format(dt);
        String filename = Registry.getInstance().getAppStoragePath() + "GPS/";
        FileUtil.CreateDir(filename);
        filename = filename + timestr + ".gps";
        if(FileUtil.WriteTxtFile(content,filename)){

            return filename;
        }
        return "";



    }
    @JavascriptInterface
    public String getAppName() {
        return "meviewer";
    }

    @JavascriptInterface
    public  void exitApp() {
        BaseActivity.exitApp();
    }

    @JavascriptInterface
    public  void restartApp() {
        BaseActivity.restartApp();
    }

    @JavascriptInterface
    public String ReadTxtFile(String path) {
        path = path.replace("file:///","/");
        String str = FileUtil.ReadTxtFile(path);
        return str;
    }

    @JavascriptInterface
    public boolean setGPSServiceEnable(int sec){
        return GPSServiceWrapper.getInstance().setServiceEnabled(sec);
    }
    @JavascriptInterface
    public boolean getGPSServiceStatus(){
        return GPSServiceWrapper.getInstance().getServiceStatus();
    }

    @JavascriptInterface
    public void setGPSRecordEnable(boolean b){
        GPSServiceWrapper.getInstance().setGPSRecordEnable(b);
    }

    @JavascriptInterface
    public String getChangedGpsData(){
        return GPSServiceWrapper.getInstance().getChangedGpsData();
    }

    @JavascriptInterface
    public void changeGPSFlag(boolean a){
        if(a){
            GPSFlag = true;
        }else {
            GPSFlag = false;
        }
    }
    @JavascriptInterface
    public String getCurrentGPS(){
        if(GPSFlag){
            return GPSServiceWrapper.getInstance().getCurrentGPS();
        }else {

            return "";
        }

    }

    @JavascriptInterface
    public String importGPSFile(){
        MainActivity.getInstance().showFileChooser();
        return "";
    }

    @JavascriptInterface
    public String outputGPSFile(){
        return GPSServiceWrapper.getInstance().writeGPStoFile();
    }

    //加载修改data.json文件
    @JavascriptInterface
    public String modifyJSonFile(String id,String stroke1,String fill1,int pixelSize){
        try {
            JsonService jsonService = new JsonService(id,stroke1,fill1,pixelSize);
            jsonService.modifyJson();
            return "修改json文件成功";
        }catch (Exception e){
            e.printStackTrace();
            return "修改json文件失败";
        }
    }
   @JavascriptInterface
    public String locationinformation(){
        try {
            String  path = "storage/emulated/0/mev/data/file/locationinformation.geojson";
            return readJsonFile(path);
        }catch (Exception e){
            e.printStackTrace();
            return "读取失败";
        }

    }
    @JavascriptInterface
    public String saveTxtFile(String context,String path)  {

        /*String  path = "storage/emulated/0/mev/data/layer.json";*/
        path = path.replace("file:///","");
        Writer w= null;//写入的文本不附加在原来的后面而是直接覆盖
        try {
            w = new FileWriter(path,false);
            w.write(context);
            w.close();
            return "成功";

        } catch (IOException e) {
            e.printStackTrace();
            return "失败";
        }
    }

    @JavascriptInterface
    public String locationinformation_test(){
        try {
            return getHttpRequestData("http://192.168.8.100:15000/mev/data/file/locationinformation.geojson");

        }catch (Exception e){
            e.printStackTrace();
            return "读取失败";
        }

    }

    //加载修改data.json文件
    @JavascriptInterface
    public String readJSonFile(){
        String  path = "storage/emulated/0/mev/data/data.json";

       try {
           return readJsonFile(path);
          
       }catch (Exception e){
           e.printStackTrace();
           return "读取json文件失败";
       }
    }

    //加载修改data.json文件
    @JavascriptInterface
    public boolean DeleteLayerData(String content,String layerPath){
        try {
          /*  String removePath = jugePath(layerPath,path,datatype);
            deleteFolder(removePath);*/
            FileUtil.write(layerPath, content);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @JavascriptInterface
    public boolean AddLayerData(String content,String filepath){
        try {
         /*   JsonService jsonService = new JsonService();
            jsonService.copyFolder(oldPath,newPath);*/
            FileUtil.write(filepath, content);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    public static String getHttpRequestData(String urlPath) {

        // 首先抓取异常并处理
        String returnString = "1";
        try{
            // 代码实现以GET请求方式为主,POST跳过
            /** 1 GET方式请求数据 start*/

            // 1  创建URL对象,接收用户传递访问地址对象链接
            URL url = new URL(urlPath);

            // 2 打开用户传递URL参数地址
            HttpURLConnection connect = (HttpURLConnection) url.openConnection();

            // 3 设置HTTP请求的一些参数信息
            connect.setRequestMethod("GET"); // 参数必须大写
            connect.connect();

            // 4 获取URL请求到的数据，并创建数据流接收
            InputStream isString = connect.getInputStream();

            // 5 构建一个字符流缓冲对象,承载URL读取到的数据
            BufferedReader isRead = new BufferedReader(new InputStreamReader(isString));

            // 6 输出打印获取到的文件流
            String str = "";
            while ((str = isRead.readLine()) != null) {
                str = new String(str.getBytes(),"UTF-8"); //解决中文乱码问题
                returnString = str;
            }

            // 7 关闭流
            isString.close();
            connect.disconnect();

            // 8 JSON转List对象
            // do somthings


        }catch(Exception e){
            e.printStackTrace();
        }

        return returnString;
    }

    @JavascriptInterface
    public void loadFileBrowser(boolean isFile, String rootPath, boolean pathAll, String jsContextFunctionName) {
        Intent toFileBrowserActivity = new Intent(MainActivity.getInstance(), FileBrowserActivity.class);
        toFileBrowserActivity.putExtra(FileBrowserActivity.ARG_BOOLEAN_IS_FILE, isFile);
        toFileBrowserActivity.putExtra(FileBrowserActivity.ARG_STRING_ROOT_PATH, rootPath);
        toFileBrowserActivity.putExtra(FileBrowserActivity.ARG_BOOLEAN_PATH_ALL, pathAll);
        toFileBrowserActivity.putExtra(FileBrowserActivity.ARG_STRING_JS_CONTEXT_FUNCTION_NAME, jsContextFunctionName);
        MainActivity.getInstance().startActivityForResult(toFileBrowserActivity, FileBrowserActivity.ACTION_LOAD_FILE_BROWSER_CODE);
    }

    @JavascriptInterface
    public String read(String filepath) {
        return FileUtil.read(filepath);
    }

    @JavascriptInterface
    public void write(String filepath, String content) {
        FileUtil.write(filepath, content);
    }

    @JavascriptInterface
    public boolean isNetOk() {
        ConnectivityManager manager = ((ConnectivityManager) MainActivity.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE));
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }

        return info.isAvailable();

    }

    /*==================跳转位置保存=========================*/
    @JavascriptInterface
    public  boolean SaveJumpInfo(String contentinfo) {
        try {
            JumpViewService jumpviewservice = new JumpViewService();
            boolean m_jumpInfo =  jumpviewservice.SaveJumpInfo(contentinfo);
            return m_jumpInfo;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /*==================跳转位置读取=========================*/
    @JavascriptInterface
    public String ReadJumpInfo(){
        try {
            //locationin
            JumpViewService jumpviewservice = new JumpViewService();
            String m_jumpInfo =  jumpviewservice.ReadJumpInfo();
            return m_jumpInfo;
        }
        catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    /*==================视点位置保存=========================*/
    @JavascriptInterface
    public  boolean SaveViewInfo(String contentinfo) {
        try {
            //locationin
            ViewPointService viewpointservice = new ViewPointService();
            boolean m_viewInfo =  viewpointservice.SaveViewInfo(contentinfo);
            return m_viewInfo;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /*==================视点位置读取=========================*/
    @JavascriptInterface
    public String ReadViewInfo(){
        try {
            ViewPointService viewpointservice = new ViewPointService();
            String m_viewInfo =  viewpointservice.ReadViewInfo();
           return m_viewInfo;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 判断是JsonObject
     * @param obj
     * @return
     */
    public static boolean isJsonObject(Object obj){
        String content = obj.toString();
        try {
            JSONObject.parseObject(content);
            if (content.startsWith("{")) {
                return  true;
            }else {
                return  false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    //写数据到sdcard
    public void savePasswordToSDCard(String content) {
        // 要存储的内容

        //判断sdcard是否存在?
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return ;
        };

        try {

            File[] tschildren =MainActivity.getInstance().getExternalFilesDirs(Environment.MEDIA_MOUNTED);

            for( File filed:tschildren){
                String m_string = String.valueOf(filed).trim().substring(0, String.valueOf(filed).indexOf("Android")-1) ;
                System.out.println(m_string);
            }

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                System.out.println("Sdcard可用");
            } else {
                System.out.println("Sdcard不可用");
            }
            String read = FileUtil.read("/storage/9016-4EF8/parameter.json");
            System.out.println(read);
            verifyStoragePermissions(MainActivity.getInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //读取SD卡中文件的方法
    //定义读取文件的方法:
    public String readFromSD(String filename) throws IOException {
        StringBuilder sb = new StringBuilder("");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            System.out.println("安排手里的牌收到了");
            System.out.println(filename);
            //打开文件输入流
            File file=new File(filename);
            FileInputStream input = new FileInputStream(file);
            byte[] temp = new byte[1024];

            int len = 0;
            //读取文件内容:
            while ((len = input.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            //关闭输入流
            input.close();
        }
        return sb.toString();
    }

    /**
     * 在对sd卡进行读写操作之前调用这个方法
     * Checks if the app has permission to write to device storage
     * If the app does not has permission then the user will be prompted to grant permissions
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }
    }
}
